package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.Collections;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.blobstore.BlobKeyProcess;
import com.tubeonfire.entity.SiteConfig;
import com.tubeonfire.model.admin.SiteConfigModel;
import com.tubeonfire.util.IdUniqueHelper;

@SuppressWarnings("serial")
public class ConfigServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(ConfigServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			String obj = req.getParameter("obj");
			SiteConfig siteConfig = SiteConfigModel.get();
			if (siteConfig == null) {
				siteConfig = new SiteConfig();
				siteConfig.setId(IdUniqueHelper.getId());
				SiteConfigModel.insert(siteConfig);
			}
			req.setAttribute("siteConfig", siteConfig);
			if (obj != null && obj.equals("seo")) {
				req.getRequestDispatcher("/admin/form_seo.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("logo")) {
				req.getRequestDispatcher("/admin/form_logo.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("system")) {
				req.getRequestDispatcher("/admin/form_system.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("social")) {
				req.getRequestDispatcher("/admin/form_social.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("slideshow")) {
				req.getRequestDispatcher("/admin/form_slideshow.jsp").forward(
						req, resp);
			} else if (obj != null && obj.equals("cache")) {
				req.getRequestDispatcher("/admin/form_cache.jsp").forward(req,
						resp);
			} else {
				req.getRequestDispatcher("/admin/error.jsp").forward(req, resp);
			}

		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession session = req.getSession();
			String obj = req.getParameter("obj");
			SiteConfig siteConfig = SiteConfigModel.get();
			if (obj != null && obj.equals("seo")) {
				String siteName = req.getParameter("siteName");
				String siteTitle = req.getParameter("siteTitle");
				String siteDescription = req.getParameter("siteDescription");
				String siteKeyword = req.getParameter("siteKeyword");
				String analyticCode = req.getParameter("analyticCode");
				if (siteName != null && !siteName.isEmpty()) {
					siteConfig.setSiteName(siteName);
				}
				if (siteTitle != null && !siteTitle.isEmpty()) {
					siteConfig.setSiteTitle(siteTitle);
				}
				if (siteKeyword != null && !siteKeyword.isEmpty()) {
					siteConfig.setSiteKeyword(siteKeyword);
				}
				if (siteDescription != null && !siteDescription.isEmpty()) {
					siteConfig.setSiteDescription(siteDescription);
				}
				if (analyticCode != null && !analyticCode.isEmpty()) {
					siteConfig.setAnalyticCode(analyticCode);
				}
				SiteConfigModel.insert(siteConfig);
				session.setAttribute("success", "Action success !");
				req.setAttribute("siteConfig", siteConfig);
				req.getRequestDispatcher("/admin/form_seo.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("logo")) {
				String slogan = (String) req.getParameter("slogan");
				String imgKey = BlobKeyProcess.getBlobKey(req, "image");
				if (slogan != null && !slogan.isEmpty()) {
					siteConfig.setLogoSlogan(slogan);
				}
				if (imgKey == null || imgKey.isEmpty()) {
					siteConfig.setLogoKey("/images/logo.png");
				} else {
					siteConfig.setLogoKey(imgKey);
				}
				SiteConfigModel.insert(siteConfig);
				session.setAttribute("success", "Action success !");
				resp.sendRedirect("/admin/config?obj=logo");
			} else if (obj != null && obj.equals("social")) {
				String twiterLink = (String) req.getParameter("twiterLink");
				String twiterName = (String) req.getParameter("twiterName");
				String facebookLink = (String) req.getParameter("facebookLink");
				String facebookAdminId = (String) req
						.getParameter("facebookAdminId");
				if (twiterLink != null && !twiterLink.isEmpty()) {
					siteConfig.setTwiterLink(twiterLink);
				}
				if (twiterName != null && !twiterName.isEmpty()) {
					siteConfig.setTwiterName(twiterName);
				}
				if (facebookLink != null && !facebookLink.isEmpty()) {
					siteConfig.setFacebookLink(facebookLink);
				}
				if (facebookAdminId != null && !facebookAdminId.isEmpty()) {
					siteConfig.setFacebookAdminId(facebookAdminId);
				}
				SiteConfigModel.insert(siteConfig);
				session.setAttribute("success", "Action success !");
				req.setAttribute("siteConfig", siteConfig);
				req.getRequestDispatcher("/admin/form_social.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("slideshow")) {
				String slideOption = (String) req.getParameter("slideOption");
				if (slideOption != null && !slideOption.isEmpty()) {
					siteConfig.setSlideStyle(slideOption);
				}
				SiteConfigModel.insert(siteConfig);
				session.setAttribute("success", "Action success !");
				req.setAttribute("siteConfig", siteConfig);
				req.getRequestDispatcher("/admin/form_slideshow.jsp").forward(
						req, resp);
			} else if (obj != null && obj.equals("system")) {
				String strAdminEmail = (String) req.getParameter("adminEmail");
				String strDisplayObject = (String) req
						.getParameter("displayObject");
				String strPlaylistQuantity = (String) req
						.getParameter("homePagePlaylistQuantity");
				String strChannelQuantity = (String) req
						.getParameter("homePageChannelQuantity");
				String strTubeQuantity = (String) req
						.getParameter("homePageTubeQuantity");
				if (strAdminEmail != null && strAdminEmail.length() > 0) {
					siteConfig.setAdminEmail(strAdminEmail);
				}
				try {
					siteConfig.setHomePageDisplayObject(Integer
							.parseInt(strDisplayObject));
				} catch (Exception e) {
					siteConfig.setHomePageBlockQuantity(2);
				}
				try {
					siteConfig
							.setHomePageBlockQuantity(Integer.parseInt(siteConfig
									.getHomePageDisplayObject() == 1 ? strPlaylistQuantity
									: strChannelQuantity));
				} catch (Exception e) {
					siteConfig.setHomePageBlockQuantity(4);
				}
				try {
					siteConfig.setHomePageTubePerBlockQuantity(Integer
							.parseInt(strTubeQuantity));
				} catch (Exception e) {
					siteConfig.setHomePageTubePerBlockQuantity(6);
				}
				SiteConfigModel.insert(siteConfig);
				session.setAttribute("success", "Action success !");
				req.setAttribute("siteConfig", siteConfig);
				req.getRequestDispatcher("/admin/form_system.jsp").forward(req,
						resp);
			} else if (obj != null && obj.equals("cache")) {
				Cache cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
				cache.clear();
				session.setAttribute("success", "Action success !");
				req.getRequestDispatcher("/admin/form_cache.jsp").forward(req,
						resp);
			} else {
				resp.sendError(4004, "Invalid parameter !");
			}

		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}
}
